layui.config({base: '/static/js/'}).use(['jquery', 'layer', 'api', 'util'], function () {
    var $ = layui.jquery, layer = layui.layer, api = layui.api, util = layui.util;

    $(".blogLogin").on("click", function () {
        layer.open({
            title: false,
            type: 1,
            fixed: false,
            content: $("#blueLoginDiv"),
            area: ['400px', '300px'],
            btn: ['登录', '取消'],
            btn1: function (index) {
                var data = getFormData("loginForm");
                api.login(data, function (res) {
                    if (res.code === 0) {
                        layer.close(index);
                        localStorage.setItem('token', res.data);
                        location.reload();
                    } else {
                        layer.msg(res.msg, {shift: 6});
                    }
                });
            }
        });
    });
    $('.blogLogout').on('click', function () {
        api.logout(function () {
            location.href = "/";
            localStorage.removeItem("token");
        });
    });

    // 添加链接
    $(".addLink").on("click", function () {
        openLinkForm(function () {
            return getFormData("linkForm");
        });
    });
    // 修改链接
    $('.editLink').on('click', function () {
        var $a = $(this).prev('a'), id = $a.attr('id');
        var oldData = {
            "title": $a.text(),
            "url": $a.attr('href')
        };
        // 设置表单
        for (var key in oldData) {
            $("#linkForm #" + key).val(oldData[key]);
        }
        openLinkForm(function () {
            var newData = getFormData("linkForm");
            newData['link.id'] = id;
            return newData;
        });
    });

    // 打开链接窗口,通过回调函数获取表单数据
    function openLinkForm(getData) {
        layer.open({
            title: false,
            type: 1,
            fixed: false,
            content: $("#blueLinkDiv"),
            area: ['400px', '300px'],
            btn: ['提交', '取消'],
            btn1: function (index) {
                api.saveLink(getData(), function (res) {
                    if (res.code === 0) {
                        layer.close(index);
                        location.reload();
                    } else {
                        layer.msg(res.msg, {shift: 6});
                    }
                });
            }
        });
    }

    $("#keyword").on('keypress', function (event) {
        if (event.keyCode === 13) {
            var keyword = $("#keyword").val();
            if (keyword === null || keyword === '') {
                layer.msg('请输入关键字搜索...', {shift: 6});
                return;
            }
            location.href = "/searchBlog?keyword=" + keyword;
        }
    });
});